﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Common;
using TomNet.IMSC.Model.DbModels.Organization;
using TomNet.IMSC.Web.Common;
using TomNet.IMSC.Web.Filters;
using TomNet.IMSC.Web.Models.ApiParams;
using TomNet.Web.Mvc.UI;
using TomNet.Web.WebApi;

namespace TomNet.IMSC.Web.Controllers.API
{
    [Description("API-账户")]
    [ApiAuthentication]
    public class CommonController : BaseApiController
    {
        public IAreaContract AreaContract { get; set; }
        public IImagesContract ImagesContract { get; set; }
        public IImageGroupContract ImageGroupContract { get; set; }
        public ISMSCodeContract SMSCodeContract { get; set; }
        public IUsersLoginContract UsersLoginContract { get; set; }
        public IOptionsContract OptionsContract { get; set; }







        [Description("API-区域列表")]
        public IHttpActionResult ttGetAreaList([FromBody]Users u)     
        {

            var query = AreaContract.Entities.Where(m => m.ParentID.Equals(u.CityID));


            var result = new AjaxResult("读取成功", AjaxResultType.Success, query.ToList());
            return Token(result, "");

        }


        [Description("API-上传图片")]
        public IHttpActionResult ttUploadImageModel([FromBody]ImagesParamsModel entity)
        {

            if (entity == null)
            {
                var result = new AjaxResult("参数无效", AjaxResultType.Error, new object[] { });
                return Token(result, "");
            }

            MemoryStream ms = new MemoryStream(Convert.FromBase64String(entity.Imagedata));
            byte[] bt = ms.ToArray();
            var oStream = new MemoryStream(bt);

            string m_saveName = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
            string m_savePath = "/Images/" + ImageGroupContract.GetByKey(entity.GroupID).ImagePath + "/";
            string m_exName = "jpg";


            if (Directory.Exists(BaseWebApiExt.GetMapPath(m_savePath)) == false)
            {
                Directory.CreateDirectory(BaseWebApiExt.GetMapPath(m_savePath));
            }

            string m_fileName = m_saveName + "." + m_exName;

            System.Drawing.Image img = System.Drawing.Image.FromStream(oStream);
            img.Save(BaseWebApiExt.GetMapPath(m_savePath) + m_fileName, ImageFormat.Jpeg);   //保存

            Images model = new Images();
            model.GroupID = entity.GroupID;
            model.InterfixID = entity.InterfixID;
            model.ImageType = entity.ImageType;
            model.ImagePath = m_savePath;
            model.FileName = m_fileName;
            model.ShowIndex = 0;
            model.Tag = "";
            model.Remark = "";


            var count = ImagesContract.Insert(model);

            if (count > 0)
            {
                var result = new AjaxResult("上传成功", AjaxResultType.Success, model);
                return Token(result, "");
            }
            else
            {
                var result = new AjaxResult("上传失败", AjaxResultType.Error);
                return Token(result, "");
            }

        }

        [Description("API-删除图片")]
        public IHttpActionResult ttDelImageModel([FromBody]Images entity)
        {
            if (entity == null)
            {
                var result = new AjaxResult("参数无效", AjaxResultType.Error, new object[] { });
                return Token(result, "");
            }


            var model = ImagesContract.GetByKey(entity.Id);
            if (model == null)
            {
                var result = new AjaxResult("无此数据", AjaxResultType.Error, new object[] { });
                return Token(result, "");
            }

            var count = ImagesContract.UpdateDirect(m => m.Id == model.Id, m => new Images { IsDeleted = true });

            
            if (count > 0)
            {
                var result = new AjaxResult("删除成功", AjaxResultType.Success);
                return Token(result, "");
            }
            else
            {
                var result = new AjaxResult("删除失败", AjaxResultType.Error);
                return Token(result, "");
            }

        }

        [Description("API-获得修改密码验证码")]
        public IHttpActionResult RePassSMSCode()
        {
            int UserID = BaseWebApiExt.GetUserIDByToken();
            if (UsersLoginContract.Entities.Count(p => p.UserID == UserID) == 0)
            {
                return Token(new AjaxResult("无效用户", AjaxResultType.Error), "");
            }
            SMSCode s = new SMSCode();
            s.Code = new Random(DateTime.Now.Millisecond).Next(0, 999999);
            s.CreatedTime = DateTime.Now;
            s.IsDeleted = false;
            s.IsLocked = false;
            s.SmsType = 1;
            s.State = 1;
            SMSCodeContract.Insert(s);
            UsersLogin ul = UsersLoginContract.Entities.FirstOrDefault(p => p.UserID == UserID);
            ul.SMSCodeID = s.Id;
            UsersLoginContract.Update(ul);
            var result = SendMessage.SendMessgeYanZhengMa(ul.LoginName, s.Code.ToString("000000"));
            return Token(result, "");

        }

        [Description("API-修改密码")]
        public IHttpActionResult RePass([FromBody]RePassParamsModel u)
        {
            int UserID = BaseWebApiExt.GetUserIDByToken();
            UsersLogin ul = UsersLoginContract.Entities.FirstOrDefault(p => p.UserID == UserID);

            if (Convert.ToInt32(u.SMSCode) == SMSCodeContract.Entities.FirstOrDefault(p => p.Id == ul.SMSCodeID).Code)
            {
                ul.LoginPass = u.PassWord;
                UsersLoginContract.Update(ul);
                var result = new AjaxResult("成功", AjaxResultType.Success);
                return Token(result, "");
            }
            return Token(new AjaxResult("验证码错误", AjaxResultType.Error), "");
        }

        [Description("API-获得忘记密码验证码")]
        [AllowAnonymous]
        public IHttpActionResult NewPassSMSCode([FromBody]RePassParamsModel u)
        {
            if (UsersLoginContract.Entities.Count(p => p.LoginName == u.LoginName && p.State>0) == 0)
            {
                return Token(new AjaxResult("无效用户", AjaxResultType.Error), "");
            }
            SMSCode s = new SMSCode();
            s.Code = new Random(DateTime.Now.Millisecond).Next(0, 999999);
            s.CreatedTime = DateTime.Now;
            s.IsDeleted = false;
            s.IsLocked = false;
            s.SmsType = 1;
            s.State = 1;
            SMSCodeContract.Insert(s);
            UsersLogin ul = UsersLoginContract.Entities.FirstOrDefault(p => p.LoginName == u.LoginName && p.State > 0);
            ul.SMSCodeID = s.Id;
            UsersLoginContract.Update(ul);
            var result = SendMessage.SendMessgeYanZhengMa(ul.LoginName, s.Code.ToString("000000"));
            return Token(result, "");

        }

        [Description("API-重置密码")]
        [AllowAnonymous]
        public IHttpActionResult NewPass([FromBody]RePassParamsModel u)
        {
            if (UsersLoginContract.Entities.Count(p => p.LoginName == u.LoginName && p.State > 0) == 0)
            {
                return Token(new AjaxResult("无效用户", AjaxResultType.Error), "");
            }
            UsersLogin ul = UsersLoginContract.Entities.FirstOrDefault(p => p.LoginName == u.LoginName && p.State > 0);

            if (Convert.ToInt32(u.SMSCode) == SMSCodeContract.Entities.FirstOrDefault(p => p.Id == ul.SMSCodeID).Code)
            {
                ul.LoginPass = u.PassWord;
                UsersLoginContract.Update(ul);
                var result = new AjaxResult("成功", AjaxResultType.Success);
                return Token(result, "");
            }
            return Token(new AjaxResult("验证码错误", AjaxResultType.Error), "");
        }
        [AllowAnonymous]
        [Description("API-获得版本号")]
        public IHttpActionResult ttGetVersionInfo()
        {

            var VersionModel = OptionsContract.Entities.Where(m => m.Name == "VersionCode").FirstOrDefault();//版本号
            var UpdateUrlModel = OptionsContract.Entities.Where(m => m.Name == "UpdateUrl").FirstOrDefault();//APP更新地址
            var UpdateInfoModel = OptionsContract.Entities.Where(m => m.Name == "UpdateInfo").FirstOrDefault();//更新说明

            if (VersionModel == null || UpdateUrlModel == null || UpdateInfoModel == null)
            {
                var result = new AjaxResult("失败", AjaxResultType.Error);
                return Token(result, "");
               
            }
            else
            {
                VersionInfoModel query = new VersionInfoModel();
                query.VersionStr = VersionModel.Remark;
                query.VersionCode = VersionModel.Value;
                query.UpdateUrl = UpdateUrlModel.Value;
                query.UpdateInfo = UpdateInfoModel.Value;

                var result = new AjaxResult("成功", AjaxResultType.Success, query);
                return Token(result, "");
            }             
                        
        }




    }
}
